package comic;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.drawable.Drawable;

public class XKCD extends Comic {

	private static final long serialVersionUID = 5933222196106454593L;

	@Override
	public String get_display_name() {
		return "xkcd";
	}

	@Override
	public int get_first_comic_n() {
		return 1;
	}

	@Override
	public int getLatest() throws MalformedURLException, IOException {
		String content = get_website_content("http://m.xkcd.com/");
		String result = content.replaceAll(
				".*<a href=\"/(\\d+)/\" accesskey=\"p\">.*", "$1");

		return Integer.parseInt(result) + 1; // result is the second to last
												// comic;
	}

	@Override
	public Strip getStrip(int id) throws MalformedURLException, IOException {
		int latest = getLatest();
		Strip s = new Strip();

		if (id < first_comic)
			id = first_comic;
		else if (id > latest)
			id = latest;
		s.id = id;

		String url = String.format("http://m.xkcd.com/%d/", id);
		String content = get_website_content(url);

		String regex = ".*<title>xkcd: (.*?)</title>.*";
		s.title = content.replaceAll(regex, "$1");

		regex = ".*<img id=\"comic\" src=\"(.*?)\" title=.*";
		URL image_url = new URL(content.replaceAll(regex, "$1"));
		s.image = Drawable.createFromStream(image_url.openStream(), "");

		regex = String.format(".*title=\"(.*?)\" alt=.*", image_url);
		String result = content.replaceAll(regex, "$1");
		s.text = result.replace("&#39;", "'");

		return s;
	}

}
